<template>
    <div>
      <allHead>
        
        <template v-slot:mid>教案生成助手</template>
      </allHead>
  
      <div class="bd">

        
        <div class="bot answer" >
            AI:
            <span>您好！将为您生成{{book.editions}}-{{book.textClass}}{{book.term}}-{{book.subject}}-{{book.unit}}-{{book.content}}的相关教案，您可以指导我修改。</span>
        </div>

        <div class="chat" v-for="item in conversation">
          
          <div class="user question"  v-if="item.role === 'user'">
            <span>{{item.content}}</span>
          </div>
          <div class="bot answer" v-if="item.role === 'assistant'">
            AI:
            <span v-katex v-html="item.content"></span>
          </div>
          
        </div>
        <div v-if="!finish">
          <van-loading vertical>
            <template #icon>
              <van-icon name="star-o" size="30" />
            </template>
            生成中，请稍等...
          </van-loading>
        </div>
  
      </div>
  
      <div class="ft">
        <div class="input">
          <input type="text" placeholder="请输入您的问题" v-model="question">
          <button @click="send">发送</button>
        </div>
      </div>
    </div>
  </template>
  
  <script setup>
  import allHead from "@/components/allHead.vue";
  import { onMounted, ref } from 'vue'
  import axios from 'axios'
  import {useBookStore} from '@/stores/bookStore.js';
  import {marked} from 'marked'

  const bookStore = useBookStore();

  const book = ref(bookStore.book.book||{})

  const conversation = ref([])

  const question = ref('')

  const finish = ref(true)
// 发送请求
  onMounted(async() => {

    const msg = {
      role: "assistant",
      content: `生成${book.value.editions}-${book.value.textClass}${book.value.term}-${book.value.subject}-${book.value.unit}-${book.value.content}的相关教案，要包括教学设计，教学内容，教学活动安排，时间分配，预期成果，教学设计要至少包括三个互动环节。`
    }
    postData(msg);
      
    // console.log('请求完成')
    // conversation.value.push({
    //   role: "assistant",
    //   content: res.data.content
    // })
    //console.log(res.data.content,514654654)

  })

// 发送请求
const send = async () => {
  if (question.value.trim() === "") return;

  // 添加用户消息到对话
  const userMessage = {
    role: "user",
    content: question.value
  };
  conversation.value.push(userMessage);

  // 清空输入框
  question.value = "";

  // 构造请求消息
  const msg = {
    role: "user",
    content: question.value
  };

 postData(msg);
};

const postData = async (msg) => {
    finish.value = false;
    try {
      //http://localhost:3000/deepseek/chat
    const response = await fetch('http://121.43.122.26:3001/openai/chat', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(msg)
    });


    if (!response.ok) {
      throw new Error('请求失败');
    }

    const reader = response.body.getReader();
    // 创建一个解码器，默认解码 UTF-8 编码
    const decoder = new TextDecoder();
    let buffer = '';

    // 流式读取数据
    while (true) {
      const { done, value } = await reader.read();

      //数据流读取完毕
      if (done) {
        finish.value = true;
        break;
      }
      

      buffer += decoder.decode(value, { stream: true });

      // 按行分割数据并更新页面
      const lines = buffer.split('\n');
      buffer = lines.pop(); // 保留未完成的最后一行

      for (const line of lines) {
        appendContent(line);
      }
    }

    // 处理剩余的缓冲区数据
    if (buffer) {
      appendContent(buffer);
    }
  } catch (error) {
    console.error('请求失败', error);
    appendContent('请求失败，请稍后重试');
  }
};
// 追加内容到对话
const appendContent = (content) => {
  const lastMessage = conversation.value[conversation.value.length - 1];

  // 转换 Markdown 内容
  const renderedContent = marked(content)

  if (lastMessage && lastMessage.role === 'assistant') {
    // 如果最后一条消息是 AI 的回复，则追加内容
    lastMessage.content += renderedContent;
  } else {
    // 否则创建一条新的 AI 回复消息
    conversation.value.push({
      role: "assistant",
      content: renderedContent
    });
  }
};

  </script>
  
  <style lang="css" scoped>
.bd {
  height: calc(100vh - 160px);
  background: #f5f7fa;
  overflow-y: auto;
  padding: 1rem 1rem 5rem;
  box-sizing: border-box;
}

.chat {
  margin: 1.5rem 0;
}

.bot.answer {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  gap: 0.8rem;
}
.bot.answer span {
  background: white;
  color: #333;
  padding: 1rem;
  border-radius: 0 1rem 1rem 1rem;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  max-width: 85%;
  line-height: 1.5;
  position: relative;
}

.user.question {
  display: flex;
  justify-content: flex-end;
  align-items: flex-start;
  gap: 0.8rem;
}
.user.question span {
  background: #2563EB;
  color: white;
  padding: 1rem;
  border-radius: 1rem 0 1rem 1rem;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  max-width: 85%;
  line-height: 1.5;
}

/* 角色标签 */
.bot.answer::before,
.user.question::before {
  content: attr(data-role);
  font-size: 0.8rem;
  color: #999;
  position: absolute;
  top: -1.2rem;
}

/* 加载动画 */
.van-loading {
  padding: 2rem;
  text-align: center;
  color: #666;
}
.van-icon-star-o {
  color: #2563EB;
  animation: spin 1.5s linear infinite;
}

@keyframes spin {
  100% { transform: rotate(360deg); }
}

.ft {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 1rem;
  border-top: 1px solid #eee;
  box-shadow: 0 -2px 10px rgba(0,0,0,0.05);
}

.input {
  display: flex;
  gap: 0.5rem;
  max-width: 800px;
  margin: 0 auto;
}

.input input {
  flex: 1;
  padding: 0.8rem 1.2rem;
  border: 1px solid #ddd;
  border-radius: 2rem;
  font-size: 1rem;
  background: #f8f9fa;
  transition: all 0.2s;
}

.input input:focus {
  outline: none;
  border-color: #2563EB;
  background: white;
  box-shadow: 0 0 0 3px rgba(142, 111, 247, 0.1);
}

.input button {
  padding: 0.8rem 1.5rem;
  background: #2563EB;
  color: white;
  border: none;
  border-radius: 2rem;
  font-weight: 500;
  cursor: pointer;
  transition: opacity 0.2s;
}

.input button:active {
  opacity: 0.8;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .bd {
    padding: 0.5rem 0.5rem 4rem;
    height: calc(100vh - 115px);
  }
  
  .bot.answer span,
  .user.question span {
    max-width: 90%;
    font-size: 0.9rem;
    padding: 0.8rem;
  }
  
  .ft {
    padding: 0.8rem;
  }
  
  .input input {
    padding: 0.7rem 1rem;
    font-size: 0.9rem;
  }
  
  .input button {
    padding: 0.7rem 1.2rem;
  }
}
</style>